package com.example.ajouconqueror;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

import com.example.classes.GameRoomClass;
import com.example.classes.IP;
import com.example.classes.UserApplication;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class GameRoomActivity extends Activity {
	//GameRoomActivity activity. In this activity you can enter the selected room...
	
	
	//variables for this activity
	ListView list;
	GameRoomAdapter adapter;
	ArrayList<GameRoomClass> Rooms;
	Thread t = null;
	GameRoomClass a;
	IP ip  = new IP();
	private final String HOST = ip.ip;
	private final int PORT = 8080;
	private final String PATH_GET = "/AjouConquerorServer-war/webresources/GameRoom/getRooms";
	private final String PATH_POST = "/AjouConquerorServer-war/webresources/GameRoom/AddRoom";
	private String path;
	UserApplication UserApp;

	private String MIME = "text/plain";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_game_room);
		UserApp = (UserApplication) getApplication();
		Rooms = new ArrayList<GameRoomClass>();
		setData();

		adapter = new GameRoomAdapter(GameRoomActivity.this, Rooms);

		list = (ListView) findViewById(R.id.list);
		list.setAdapter(adapter);
	}

	public void onClick(View v) {
		// When you click create button the addroom AsyncTask is started for creating room.
		path = PATH_POST;
		addRoom t = new addRoom();
		t.execute();
	}

	private class addRoom extends AsyncTask<Void, Void, String> {
		@Override
		protected void onPreExecute() {
			
		}

		@Override
		protected String doInBackground(Void... params) {
			String result = "false";
			//For making room, you have to input the user's id
			//This id will be room master.
			String id = UserApp.getUserid();
			//And room's name is (user's id)'s room.
			String pas = UserApp.getUserid() + "'s Room";
			HttpHost target = new HttpHost(HOST, PORT);
			HttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost(path);

			// set the MIME type for POST message body.
			post.setHeader("Content-Type", "application/x-www-form-urlencoded");

			HttpEntity entity = null;

			List<NameValuePair> idpair = new ArrayList<NameValuePair>();
			idpair.add(new BasicNameValuePair("uid", id));
			idpair.add(new BasicNameValuePair("pass", pas));

			try {
				post.setEntity(new UrlEncodedFormEntity(idpair));

				HttpResponse response = client.execute(target, post);
				if (response.getStatusLine().getStatusCode() < 400) {
					result = "get";
				}

				entity = response.getEntity();
				String str = EntityUtils.toString(entity);
				result = str;
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				Log.i("errorr:", "UnsupportedEncodingException");
			} catch (ClientProtocolException e) {
				e.printStackTrace();
				Log.i("errorr:", "ClientProtocolException");
			} catch (IOException e) {
				e.printStackTrace();
				Log.i("errorr:", "IOException");
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			//If room is made , the room id is set in userapp for room master.
			// and the TeamSelection activity is started.
			int roomid = Integer.parseInt(result);
			UserApp.setRoomid(roomid);
			UserApp.setTeam(1);
			Intent i = new Intent(GameRoomActivity.this, TeamSelection.class);
			startActivity(i);
		}
	}

	public void RenewButtonClick(View v) {
		//If you click the renew button, you can renew the data and adapter's data is renewed
		setData();
		adapter.Renew(Rooms);
	}

	public void backButtonClick(View v) {
		//If you click the backbutton, you can go to before activity.
		finish();
	}

	private void setData() {
		//this is setDate function for getting data.
		try {
			path = PATH_GET;
			dataset t = new dataset();
			t.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private class dataset extends
			AsyncTask<Void, Void, ArrayList<GameRoomClass>> {
		//In this AsyncTask, you can get roomdata in server.
		// you can get all room objects from the server.
		// And in onPostExecute renew the adapter.

		@Override
		protected void onPreExecute() {
			
		}

		@Override
		protected ArrayList<GameRoomClass> doInBackground(Void... params) {

			ArrayList<GameRoomClass> result = null;

			HttpHost target = new HttpHost(HOST, PORT);
			HttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(path);
			// if the service provides more than one content type (MIME),
			// we can set preferred type with the "Accept" header field:
			get.setHeader("content-type", "application/json");
			HttpEntity entity = null;
			try {
				HttpResponse response = client.execute(target, get);

				if (response.getStatusLine().getStatusCode() != 200) {
					Log.i("AC", "Error in HTTP GET. Status code: "
							+ response.getStatusLine().getStatusCode());
					return null;
				}
				entity = response.getEntity();
				String str = EntityUtils.toString(entity, "utf-8");
				result = JSONToRoomarray(str);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {

			}
			return result;
		}

		@Override
		protected void onPostExecute(ArrayList<GameRoomClass> result) {
			if (result != null) {
				Rooms = result;
				adapter.Renew(Rooms);
			}
		}
	}

	private ArrayList<GameRoomClass> JSONToRoomarray(String json) {
		// This class convert the Json type to ArrayList<GameRoomClass> type.
		Gson gson = new Gson();
		Type t = new TypeToken<ArrayList<GameRoomClass>>() {
		}.getType();
		ArrayList<GameRoomClass> p = gson.fromJson(json, t);
		return p;
	}

}
